<?php
class MediaPlayerWidget extends CWidget
{
    private $_id;
    public $scriptUrl;
    public $flashPlayer='player.swf';
    public $width=480;
    public $height=270;
    public $useAbsoluteUrl=false;
    
    /**
    * @var string
    */
    public $file;
    public $image;
    /**
    *  {@see http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/15995/jw-embedder-reference-guide#playlists}
    *  {@see http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12536/configuration-options#playlistprop}
    * 
    * array(
    *   array(
    *       'file'=>'', 
    *       'image'=>'', 
    *       'duration'=>'', 
    *       'start'=>'', 
    *       'title'=>'', 
    *       'description'=>'', 
    *       'streamer'=>'', 
    *       'provider'=>'', 
    *       'levels'=>'', 
    *   ),
    * )
    * @var array
    */
    public $playlist=array();
    /**
    * {@see http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/15995/jw-embedder-reference-guide#levels}
    * 
    * array(
    *   array(
    *       'bitrate'=>'', 
    *       'file'=>'', 
    *       'width'=>'', 
    *   ),
    * )
    * @var array
    */
    public $levels=array();
    /**
    * {@see http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/15995/jw-embedder-reference-guide#plugins}
    * 
    * @var array
    */
    public $plugins=array();
    /**
    * {@see http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12540/javascript-api-reference#Events}
    * 
    * @var array
    */
    public $events=array();
    /**
    * {@see http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/15995/jw-embedder-reference-guide#players}
    * 
    * @var boolean
    */
    public $usePlayers=true;
    
    public $options=array();
    
    public $htmlOptions=array();
    
    public function init()
    {
        $this->_id = $this->getId();
        $this->registerClientScript();
        parent::init();
    }
    
    public function run()
    {
        parent::run();
    }
    
    protected function registerClientScript()
    {
        if ($this->scriptUrl === null) {
            $this->scriptUrl = Yii::app()->getAssetManager()->publish(dirname(__FILE__).DIRECTORY_SEPARATOR.'assets');
        }
        
        $options = array(
            'height'=>(int) $this->height,
            'width'=>(int) $this->width,
            'events'=>array(
                'onPlay'=>'js:function(event){jQuery.fancybox.center();}',
            ),
            'plugins'=>array(
                'viral-2'=>array(),
                'gapro-2'=>array(
//                    'trackingobject'=>'_gaq',
                ),
            ),
            'viral.onpause'=>false,
            'viral.oncomplete'=>false,
            'viral.allowmenu'=>false,
            'dock'=>true,
        );
        
        if ($this->usePlayers) {
            $options['players'] = array(
                array('type'=>'html5'),
                array('type'=>'flash', 'src'=>$this->scriptUrl.'/'.$this->flashPlayer),
                array('type'=>'download'),
            );
        } else
            $options['flashplayer'] = $this->scriptUrl.'/'.$this->flashPlayer;
            
        if (is_array($this->playlist) && count($this->playlist))
        {
            $options['playlist'] = $this->playlist;
            if ($this->useAbsoluteUrl)
                $options['playlist'] = Yii::app()->request->hostInfo.Yii::app()->baseUrl.'/'.$options['playlist'];
        }
        else {           
            
            //use .mp4 or .flv
            if (! Yii::app()->user->getState('HAS_FLASH', false))
            {
                $ext = CFileHelper::getExtension($this->file);
                $this->file = substr($this->file, 0, -strlen($ext)).'mp4';
            }
            
            $options['plugins']['sharing-2'] = $options['plugins']['fbit-1'] = $options['plugins']['tweetit-1'] = array('link'=>Yii::app()->request->hostInfo.Yii::app()->baseUrl.'/'.$this->file);
            $options['file'] = $this->file;
            if ($this->useAbsoluteUrl)
            {
                $options['file'] = Yii::app()->request->hostInfo.Yii::app()->baseUrl.'/'.$options['file'];
            }
            if (empty($this->image) === false)
            {
                $options['image'] = $this->image;
                if ($this->useAbsoluteUrl)
                    $options['image'] = Yii::app()->request->hostInfo.Yii::app()->baseUrl.'/'.$options['image'];
            }
        }
            
        if (is_array($this->levels) && count($this->levels))
            $options['levels'] = $this->levels;
            
        if (is_array($this->plugins) && count($this->plugins))
            $options['plugins'] = $this->plugins;
            
        if (is_array($this->events) && count($this->events))
            $options['events'] = $this->events;
            
        if (empty($this->skin) === false)
            $options['skin'] = $this->skin;
        
        $options = CMap::mergeArray($options, $this->options);
        $options = CJavaScript::encode($options);
        $id = CHtml::encode($this->_id);
        $fancyboxOptions = array(
            'width'=>(int) $this->width,
            'height'=>(int) $this->height,
            'padding'=>0,
//            'margin'=>0,
            'centerOnScroll'=>false,
            'hideOnOverlayClick'=>true,
			
            'autoScale'=>false,
            'titleShow'=>false,
            'scrolling'=>'none',
            'onCleanup'=>'js:function(){if ($("#fancybox-content object").size()){var id=$("#fancybox-content object").attr("id");jwplayer(id).remove();}}',
            'onClosed'=>'js:function(){jQuery("#fancybox-wrap").removeClass("video");}',
            'onStart'=>'js:function(){jQuery("#fancybox-wrap").addClass("video");}',
            'onComplete'=>'js:function(){
                jwplayer(id).remove();
                jwplayer(id).setup('.$options.');
                //load playlist
                if (params != undefined)
                {
                    jwplayer(id).load(params);
                }
                
                jwplayer(id).stop();
                jwplayer(id).play();
            }',
        );
        $fancyboxOptions = CJavaScript::encode($fancyboxOptions);
        $style = '';
        if ($this->width)
            $style .= 'width:'.(int) $this->width.'px;';
            
        if ($this->height)
            $style .= 'height:'.(int) $this->height.'px;';
        $script = "
try {
jQuery('body').bind('player.play', function(event, id, params){
    if (id == '{$id}')
    {
        jQuery.fancybox('<div id=\"{$this->_id}\" style=\"{$style}\">Loading the player ...</div>', {$fancyboxOptions});
    }
});
} catch (e){}
";
        $cs = Yii::app()->clientScript;
        $cs->registerScript(__CLASS__.'#'.$id, $script, CClientScript::POS_READY);
        $cs->registerScript(__CLASS__.'#TriggerPlay', "function cms_play_video(id){jQuery('body').trigger('player.play', [id]);}", CClientScript::POS_END);
        $cs->registerScriptFile($this->scriptUrl.'/jwplayer.js', CClientScript::POS_HEAD);
        $cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.js', CClientScript::POS_HEAD);
        $cs->registerCssFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.css');
        $cs->registerCssFile(Yii::app()->theme->baseUrl.'/styles/fancybox-fix.css');
    }
}